import React from 'react';
import { Form, Input, Button, Select, Space, Alert, Typography } from 'antd';
import { ModelSelector, ApiKeyValidator } from '../index';
import { ValidationResult, LLMProvider, ModelInfo } from '../../types';

const { Option } = Select;
const { Title } = Typography;

interface LLMConfig {
  provider: LLMProvider;
  apiKey: string;
  modelName: string;
  options: {
    baseURL: string;
  };
}

interface LLMConfigTabProps {
  config: LLMConfig;
  validationResult?: ValidationResult | null;
  isLoading?: boolean;
  onChange: (config: LLMConfig) => void;
  onValidationChange: (result: ValidationResult | null) => void;
  onLoadingChange: (isLoading: boolean) => void;
}

export const LLMConfigTab: React.FC<LLMConfigTabProps> = ({
  config,
  validationResult,
  isLoading = false,
  onChange,
  onValidationChange,
  onLoadingChange
}) => {
  const [form] = Form.useForm();

  const modelLLMs = [
    { value: "anthropic" as LLMProvider, label: "Claude (Anthropic)" },
    { value: "openai" as LLMProvider, label: "OpenAI" },
    { value: "openrouter" as LLMProvider, label: "OpenRouter" },
    { value: "openai-compatible" as LLMProvider, label: "OpenAI 兼容" },
  ];

  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      
      // 检查API Key是否已验证
      if (!validationResult?.isValid) {
        // message.warning('请先验证 API Key 有效性');
        return;
      }
      
      onLoadingChange(true);
      
      // 保存配置到 Chrome Storage
      chrome.storage.sync.set(
        { llmConfig: values },
        () => {
          if (chrome.runtime.lastError) {
            console.error(`保存失败: ${chrome.runtime.lastError.message}`);
          } else {
            console.log("LLM配置保存成功！");
          }
          onLoadingChange(false);
        }
      );
    } catch (error) {
      console.error("请检查表单字段");
      onLoadingChange(false);
    }
  };

  const handleLLMChange = (value: LLMProvider) => {
    const baseURLMap = {
      openai: "https://api.openai.com/v1",
      anthropic: "https://api.anthropic.com/v1",
      openrouter: "https://openrouter.ai/api/v1",
      "openai-compatible": "https://api.openai.com/v1",
    };
    
    const newConfig = {
      provider: value,
      apiKey: "",
      modelName: "", // 清空模型名称，让用户重新选择
      options: {
        baseURL: baseURLMap[value]
      },
    };
    
    onChange(newConfig);
    form.setFieldsValue(newConfig);
    
    // 清除验证结果
    onValidationChange(null);
  };
  
  // 处理模型选择
  const handleModelChange = (modelId: string, modelInfo?: ModelInfo) => {
    const newConfig = { ...config, modelName: modelId };
    onChange(newConfig);
    form.setFieldsValue({ modelName: modelId });
  };
  
  // 处理API Key变化
  const handleApiKeyChange = (apiKey: string) => {
    const newConfig = { ...config, apiKey };
    onChange(newConfig);
    form.setFieldsValue({ apiKey });
  };
  
  // 处理Base URL变化
  const handleBaseURLChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const baseURL = e.target.value;
    const newConfig = {
      ...config,
      options: { ...config.options, baseURL }
    };
    onChange(newConfig);
    form.setFieldsValue({ options: { baseURL } });
    
    // Base URL变化时清除验证结果
    onValidationChange(null);
  };

  return (
    <div 
      style={{
        fontFamily: 'var(--eko-font-family-chinese)',
        fontSize: 'var(--eko-font-size-base)',
        lineHeight: 'var(--eko-line-height-base)',
      }}
    >
      <Title 
        level={3} 
        style={{
          fontFamily: 'var(--eko-font-family-chinese)',
          fontSize: 'var(--eko-font-size-lg)',
          fontWeight: 600,
          color: '#262626',
          marginBottom: '24px'
        }}
      >
        LLM 配置
      </Title>

      <Form 
        form={form} 
        layout="vertical" 
        initialValues={config}
        style={{
          fontFamily: 'var(--eko-font-family-chinese)'
        }}
      >
        <Form.Item
          name="provider"
          label={
            <span style={{
              fontFamily: 'var(--eko-font-family-chinese)',
              fontSize: 'var(--eko-font-size-sm)',
              fontWeight: 500,
              color: '#262626'
            }}>
              LLM 供应商
            </span>
          }
          rules={[
            {
              required: true,
              message: "请选择 LLM 供应商",
            },
          ]}
        >
          <Select 
            placeholder="选择 LLM 供应商" 
            onChange={handleLLMChange}
            style={{
              fontFamily: 'var(--eko-font-family-chinese)'
            }}
          >
            {modelLLMs.map((llm) => (
              <Option key={llm.value} value={llm.value}>
                <span style={{
                  fontFamily: 'var(--eko-font-family-chinese)'
                }}>
                  {llm.label}
                </span>
              </Option>
            ))}
          </Select>
        </Form.Item>
        
        <Form.Item
          name={["options", "baseURL"]}
          label={
            <span style={{
              fontFamily: 'var(--eko-font-family-chinese)',
              fontSize: 'var(--eko-font-size-sm)',
              fontWeight: 500,
              color: '#262626'
            }}>
              API 地址
            </span>
          }
          rules={[
            {
              required: true,
              message: "请输入 API 地址",
            },
            {
              type: 'url',
              message: '请输入有效的 URL 地址',
            },
          ]}
        >
          <Input 
            placeholder="请输入 API 地址" 
            onChange={handleBaseURLChange}
            style={{
              fontFamily: 'var(--eko-font-family-chinese)'
            }}
          />
        </Form.Item>

        <Form.Item
          name="modelName"
          label={
            <span style={{
              fontFamily: 'var(--eko-font-family-chinese)',
              fontSize: 'var(--eko-font-size-sm)',
              fontWeight: 500,
              color: '#262626'
            }}>
              模型选择
            </span>
          }
          rules={[
            {
              required: true,
              message: "请选择模型",
            },
          ]}
        >
          <ModelSelector
            provider={config.provider}
            value={config.modelName}
            onChange={handleModelChange}
            placeholder="选择或输入模型名称"
            baseURL={config.options.baseURL}
            apiKey={config.apiKey}
          />
        </Form.Item>

        <Form.Item
          name="apiKey"
          label={
            <span style={{
              fontFamily: 'var(--eko-font-family-chinese)',
              fontSize: 'var(--eko-font-size-sm)',
              fontWeight: 500,
              color: '#262626'
            }}>
              API Key
            </span>
          }
          rules={[
            {
              required: true,
              message: "请输入 API Key",
            },
          ]}
        >
          <ApiKeyValidator
            provider={config.provider}
            value={config.apiKey}
            baseURL={config.options.baseURL}
            onChange={handleApiKeyChange}
            onValidationChange={onValidationChange}
            placeholder="请输入 API Key"
            autoValidate={true}
          />
        </Form.Item>

        {/* 配置状态提示 */}
        {validationResult && (
          <div style={{ marginBottom: '16px' }}>
            {validationResult.isValid ? (
              <Alert
                message="配置验证成功"
                description="所有配置项已验证通过，可以保存配置"
                type="success"
                showIcon
              />
            ) : (
              <Alert
                message="配置需要完善"
                description="请完成 API Key 验证后再保存配置"
                type="warning"
                showIcon
              />
            )}
          </div>
        )}

        <Form.Item>
          <Space style={{ width: '100%' }}>
            <Button 
              type="primary" 
              onClick={handleSave} 
              loading={isLoading}
              style={{
                fontFamily: 'var(--eko-font-family-chinese)',
                fontSize: 'var(--eko-font-size-sm)',
                fontWeight: 500,
                height: '40px',
                borderRadius: '6px'
              }}
            >
              保存配置
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </div>
  );
};